package com.mirror.tk.api.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mirror.tk.api.common.Constant;
import com.mirror.tk.api.common.support.JwtFace;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.utils.mapper.JsonMapper;

/**
 * api接口授权认证过滤器
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LogManager.getLogger(this.getClass());

	// 需要授权的uri
	private String[] AUTH_URL = new String[] { "/lo/", "/my/" };
	// 强制不授权的uri
	private String[] NO_AUTH_URL = new String[] { "/nlo/" };

	/**
	 * 登录认证判断
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 * @author fengshi on 2016年11月17日
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 前台预检测
        if(request.getMethod().equalsIgnoreCase(RequestMethod.OPTIONS.name())){
        	return true;
        }
        // 请求的uri
        String uri = request.getRequestURI();
        // 如果是强制不认证的连接，直接放行
        for (String noAuth : NO_AUTH_URL) {
			if(uri.indexOf(noAuth) != -1){
				return true;
			}
		}
        // 是否过滤
        boolean doFilter = false;
        for (String auth : AUTH_URL) {
        	if (uri.indexOf(auth) != -1) {
                doFilter = true;
                break;
            }
		}
        // 非法访问
        if (doFilter && !JwtFace.isUserLogin(request)) {
        	logger.debug("拦截到用户的非法请求，非法地址：{}", uri);
        	response.setCharacterEncoding("UTF-8");
        	response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JsonMapper.nonDefaultMapper().toJson(new JsonResult(Constant.Global.UNAUTHORIZED, Constant.Global.UNAUTHORIZED_MSG)));
            printWriter.flush();
            printWriter.close();
        	return false;
        }
        // 合法访问
        return true;
	}
	
}
